<template>
  <el-card class="box-card">
    <div class="app-container">
      <el-form ref="formRef" :model="form" label-width="130px" :rules="rules">
        <el-form-item label="输入源配置" prop="input_type">
          <el-select v-model="form.input_type" placeholder="请选择输入源" @change="changeInputType">
            <el-option label="USB摄像头" value="0" />
            <el-option label="视频流" value="1" />
            <el-option label="网络摄像头" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="输入路径配置" prop="source">
          <el-input v-model="form.source" placeholder="输入源配置" style="width: 300px; margin-left: 10px;" />
          <el-button type="primary" style="margin-left: 10px;" @click="updateSource">保存</el-button>
        </el-form-item>
        <!-- <el-form-item label="输入视角配置">
          <el-radio-group v-model="form.input_view" prop="input_view" @change="changeInputview">
            <el-radio :label="1">单视角</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <!-- <div class="canvas-container">
           用于显示图片的canvas
          <canvas ref="imageCanvas" class="image-canvas" width="512" height="512" />
          用于绘制矩形框的canvas，初始时隐藏
          <canvas
            ref="drawCanvas"
            class="draw-canvas"
            width="512"
            height="512"
            @mousedown="startDrawing"
            @mousemove="draw"
            @mouseup="endDrawing"
            @mouseleave="endDrawing"
          />
        </div> -->
        <!-- <el-form-item class="button-container">
          <el-button type="primary" @click="captureImage">捕获</el-button>
          <el-button type="primary" @click="openDrawing">绘制检测区域</el-button>
          <el-button type="danger" @click="clearBoxes">清除</el-button>
          <el-button type="success" @click="saveBoxes">保存</el-button>
        </el-form-item> -->
        <el-form-item label="视频保存时间（分钟）">
          <el-input
            v-model="form.cutTime"
            placeholder="视频保存时间（单位为分钟）"
            style="width: 250px; text-align: center;"
          />
          <el-button type="primary" style="margin-left: 10px;" @click="updateSaveTimes">保存</el-button>

        </el-form-item>
        <el-form-item label="检测阈值配置" prop="threshold">
          <el-input-number
            v-model.number="form.threshold"
            placeholder="检测阈值输入"
            style="width: 300px"
            :min="0"
            :max="1"
            :step="0.1"
          />
          <el-button type="primary" style="margin-left: 10px;" @click="updateThreshold">保存</el-button>
        </el-form-item>
        <el-form-item label="是否开启视频保存">
          <el-switch v-model="save_Status" @change="updateStatus(0)" />
        </el-form-item>
        <el-form-item label="是否开始检测">
          <el-switch v-model="detected_Status" :disabled="isSwitchDisabled" @change="updateStatus(1)" />
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
import { Message } from 'element-ui'

export default {
  data() {
    return {
      tempData: '',
      form: {
        input_type: '',
        source: '',
        // input_view: 1,
        threshold: 0.5,
        cutTime: '',
        boxes: []
      },
      rules: {
        input_type: [{ required: true, message: '请选择输入源', trigger: 'blur' }],
        source: [{ required: true, message: '请输入输入源配置', trigger: 'blur' }],
        // input_view: [{ required: true, message: '请选择输入视角配置', trigger: 'change' }],
        threshold: [
          { required: true, message: '请输入检测阈值', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (typeof value !== 'number' || value < 0 || value > 1) {
                callback(new Error('检测阈值必须在 0 到 1 之间'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      scale: null,
      detected_Status: false,
      isSwitchDisabled: false,
      save_Status: false,
      imageSrc: null,
      isDrawing: false,
      currentBox: null
    }
  },
  created() {
    this.getConfig()
  },
  methods: {
    getConfig() {
      this.$store.dispatch('systemconfig/getConfig')
        .then(response => {
          if (response.status === 200) {
            this.tempData = response.data
            this.form.threshold = this.tempData.threshold
            this.detected_Status = this.tempData.detected_status === 0
            this.save_Status = this.tempData.save_status === 0
            this.form.input_type = this.tempData.input_type.toString()
            this.form.source = this.tempData.source
            // this.form.input_view = this.tempData.input_view
            this.form.cutTime = this.tempData.save_time
            Message({
              message: response.message,
              type: 'success',
              duration: 3000
            })
          } else {
            Message({
              message: response.message,
              type: 'error',
              duration: 3000
            })
            return
          }
        })
        .catch(error => {
          console.error('获取配置信息失败:', error)
        })
    },
    // captureImage() {
    //   const params = {
    //     input_type: this.form.input_type,
    //     source: this.form.source,
    //     input_view: this.form.input_view
    //   }
    //   if (this.form.source === '' || this.form.source === null) {
    //     Message({
    //       message: '请输入来源',
    //       type: 'error',
    //       duration: 3000
    //     })
    //     return
    //   }
    //   this.$store.dispatch('systemconfig/capture', params)
    //     .then(response => {
    //       if (response.status === 200) {
    //         this.imageSrc = 'data:image/jpg;base64,' + response.data

    //         this.drawImage(this.imageSrc)
    //         Message({
    //           message: response.message,
    //           type: 'success',
    //           duration: 3000
    //         })
    //       } else {
    //         Message({
    //           message: response.message,
    //           type: 'error',
    //           duration: 3000
    //         })
    //       }
    //     })
    //     .catch(error => {
    //       console.error('获取图像失败:', error)
    //     })
    //   // this.imageSrc = 'avatar1.png'
    // },
    // drawImage(imageSrc) {
    //   const imageCanvas = this.$refs.imageCanvas
    //   const ctxImage = imageCanvas.getContext('2d')
    //   const img = new Image()

    //   img.src = imageSrc

    //   img.onload = () => {
    //     var scale = null
    //     if (imageCanvas.width > img.width) {
    //       scale = Math.min(imageCanvas.width / img.width, imageCanvas.height / img.height)
    //     } else {
    //       scale = Math.min(img.width / imageCanvas.width, img.height / imageCanvas.height)
    //     }
    //     this.scale = scale

    //     ctxImage.drawImage(img, 0, 0, img.width / scale, img.height / scale)
    //   }
    // },
    // openDrawing() {
    //   this.isDrawing = true
    // },
    // startDrawing(e) {
    //   if (this.form.boxes.length >= (this.form.input_view === 1 ? 1 : 2)) {
    //     this.$message({
    //       message: '已达最大绘制数量',
    //       type: 'warning'
    //     })
    //     return
    //   }
    //   this.currentBox = { startX: e.offsetX, startY: e.offsetY }
    //   this.isDrawing = true
    // },
    // draw(e) {
    //   if (!this.isDrawing || !this.currentBox) return

    //   const canvas = this.$refs.drawCanvas
    //   const ctx = canvas.getContext('2d')
    //   ctx.clearRect(this.currentBox.startX, this.currentBox.startY, e.offsetX - this.currentBox.startX, e.offsetY - this.currentBox.startY)

    //   ctx.beginPath()
    //   ctx.rect(this.currentBox.startX, this.currentBox.startY, e.offsetX - this.currentBox.startX, e.offsetY - this.currentBox.startY)
    //   ctx.stroke()
    // },
    // endDrawing(e) {
    //   if (!this.isDrawing || !this.currentBox) return

    //   const ctx = this.$refs.drawCanvas.getContext('2d')
    //   ctx.stroke()

    //   this.form.boxes.push({
    //     x1: this.currentBox.startX,
    //     y1: this.currentBox.startY,
    //     width: e.offsetX - this.currentBox.startX,
    //     height: e.offsetY - this.currentBox.startY
    //   })

    //   this.redraw()

    //   this.isDrawing = false
    //   this.currentBox = null
    // },
    // clearBoxes() {
    //   this.form.boxes = []
    //   this.isDrawing = false
    //   this.currentBox = null
    //   const ctx = this.$refs.drawCanvas.getContext('2d')
    //   ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
    // },
    // saveBoxes() {
    //   this.$refs.formRef.validate((valid) => {
    //     if (valid) {
    //       if (this.form.boxes.length === 0) {
    //         this.$message({
    //           message: '请先绘制检测区域',
    //           type: 'error',
    //           duration: 3000
    //         })
    //         return
    //       }
    //       const points = []
    //       for (let i = 0; i < this.form.boxes.length; i++) {
    //         points[i] = []
    //         const box = this.form.boxes[i]
    //         points[i][0] = box.x1 * this.scale
    //         points[i][1] = box.y1 * this.scale
    //         points[i][2] = box.width * this.scale
    //         points[i][3] = box.height * this.scale
    //       }

    //       const params = {
    //         input_type: this.form.input_type,
    //         source: this.form.source,
    //         input_view: this.form.input_view,
    //         points: points
    //       }
    //       console.log('Sending data:', params)
    //       this.$store.dispatch('systemconfig/saveInput', params)
    //         .then(response => {
    //           if (response.status === 200) {
    //             Message({
    //               message: '保存系统配置成功，重启检测开关生效',
    //               type: 'success',
    //               duration: 3000
    //             })
    //           } else {
    //             Message({
    //               message: response.message,
    //               type: 'error',
    //               duration: 3000
    //             })
    //             return
    //           }
    //         })
    //         .catch(error => {
    //           console.error('保存失败:', error)
    //         })
    //     } else {
    //       console.log('表单验证失败')
    //       return false
    //     }
    //   })
    // },
    changeInputType() {
      this.$store.dispatch('systemconfig/changeInputType', this.form.input_type)
        .then(response => {
          if (response.status === 200) {
            Message({
              message: '修改成功',
              type: 'success',
              duration: 3000
            })
          } else {
            Message({
              message: response.message,
              type: 'error',
              duration: 3000
            })
            return
          }
        })
        .catch(error => {
          console.error('保存失败:', error)
        })
    },
    updateSource() {
      this.$refs.formRef.validateField('source', (valid) => {
        if (!valid) {
          this.$store.dispatch('systemconfig/updateSource', this.form.source)
            .then(response => {
              if (response.status === 200) {
                Message({
                  message: '修改成功',
                  type: 'success',
                  duration: 3000
                })
              } else {
                Message({
                  message: response.message,
                  type: 'error',
                  duration: 3000
                })
                return
              }
            })
            .catch(error => {
              console.error('保存失败:', error)
            })
        } else {
          console.log('配置源验证失败')
          return false
        }
      })
    },
    updateThreshold() {
      this.$refs.formRef.validateField('threshold', (valid) => {
        if (!valid) {
          this.$store.dispatch('systemconfig/updateThreshold', this.form.threshold)
            .then(response => {
              console.log(response)
              if (response.status === 200) {
                // this.tempData = response.data
                // this.form.threshold = this.tempData.threshold
                Message({
                  message: '修改成功',
                  type: 'success',
                  duration: 3000
                })
              } else {
                Message({
                  message: response.message,
                  type: 'error',
                  duration: 3000
                })
                return
              }
            })
            .catch(error => {
              console.error('保存失败:', error)
            })
        } else {
          console.log('阈值验证失败')
          return false
        }
      })
    },
    updateSaveTimes() {
      console.log(this.form.cutTime)
      this.$store.dispatch('systemconfig/updateSaveTimes', this.form.cutTime)
        .then(response => {
          if (response.status === 200) {
            Message({
              message: '修改成功',
              type: 'success',
              duration: 3000
            })
          } else {
            Message({
              message: response.message,
              type: 'error',
              duration: 3000
            })
            return
          }
        })
        .catch(error => {
          console.error('保存失败:', error)
        })
    },
    updateStatus(flag) {
      // 更新检测状态
      console.log(flag)
      if (flag === 1) {
        var status = this.detected_Status ? 0 : 1
        this.isSwitchDisabled = true
        this.$store.dispatch('systemconfig/updateDetectStatus', status)
          .then(response => {
            console.log(response)
            if (response.status === 200) {
              this.tempData = response
              // this.detected_Status = this.tempData.status
              Message({
                message: '修改成功',
                type: 'success',
                duration: 3000
              })
              this.isSwitchDisabled = false
            } else {
              console.log(response.message)
              Message({
                message: '读取失败',
                type: 'error',
                duration: 3000
              })
              this.detected_Status = 0
              this.isSwitchDisabled = false
              return
            }
          })
          .catch(error => {
            console.error('读取失败:', error)
            this.isSwitchDisabled = false
          })
      } else { // 更新视频保存状态
        var status_time = this.save_Status ? 0 : 1
        this.$store.dispatch('systemconfig/updateSaveStatus', status_time)
          .then(response => {
            console.log(response)
            if (response.status === 200) {
              this.tempData = response

              // this.detected_Status = this.tempData.status
              Message({
                message: response.message,
                type: 'success',
                duration: 3000
              })
            } else {
              Message({
                message: response.message,
                type: 'error',
                duration: 3000
              })
              return
            }
          })
          .catch(error => {
            console.error('保存失败:', error)
          })
      }
    },
    changeInputview(value) {
      this.form.input_view = value
      if (value === 1) {
        this.form.boxes = this.form.boxes.slice(0, 1)
      } else if (value === 2) {
        this.form.boxes = this.form.boxes.slice(0, 2)
      }
      this.redraw()
    },
    redraw() {
      const ctx = this.$refs.drawCanvas.getContext('2d')
      ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
      this.form.boxes.forEach(box => {
        ctx.beginPath()
        ctx.rect(box.x1, box.y1, box.width, box.height)
        ctx.stroke()
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  max-width: 800px;
  margin: 30px auto;
}

.canvas-container {
  position: relative;
  width: 100%;
  max-width: 512px;
  margin: 0 auto;
}

.canvas-container {
  position: relative;
  width: 512px;
  height: 512px;
}

.image-canvas,
.draw-canvas {
  position: absolute;
  top: 0;
  left: 0;
}

.image-canvas {
  z-index: 1;
}

.draw-canvas {
  z-index: 2;
  border: 2px solid red;
}

.button-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px 0;
}

.el-button {
  margin-left: 10px;
}

.button-container>.el-button:first-child {
  margin-left: 0;
}
</style>
